<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-4-2
 * Time: 上午9:44
 */

namespace api\modules\chedai\controllers;


use api\modules\chedai\models\Login;
use common\components\tools\Tools;
use common\models\credit_app\ApiToken;
use common\models\credit_app\Member;
use wodrow\yii\rest\Controller;
use yii\base\ErrorException;

class SiteController extends Controller
{
    /**
     * 登录
     * @desc get/post
     * @param string $u_name 用户名
     * @param string $u_password 密码
     * @return array
     * @throws ErrorException
     */
    public function actionLogin($u_name, $u_password)
    {
        $login_form = new Login();
        if (!$login_form->load(\Yii::$app->request->post(), '')||!$login_form->validate()){
            return $login_form->errors;
        }
        $member = Member::findIdentityByUNameAndUPassword($u_name, $u_password);
        if ($member->u_dp_type!=$member::U_DP_TYPR_DOT){
            throw new ErrorException("非网店人员不允许登录");
        }
        $api_token = ApiToken::findOne(['tk_uid' => $member->u_id]);
        if (!$api_token){
            $api_token = new ApiToken();
            $api_token->tk_uid = $member->u_id;
        }
        $api_token->tk_token = \Yii::$app->security->generateRandomString(64);
        $api_token->tk_expiration = time() + 86400;
        if (!$api_token->save()){
            throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($api_token));
        }
        $o['u_id'] = $member->u_id;
        $o['u_name'] = $member->u_name;
        $o['u_realname'] = $member->u_realname;
        $o['u_mobile'] = $member->u_mobile;
        $o['u_token'] = $api_token->tk_token;
        $o['u_token_exp'] = $api_token->tk_expiration;
        $o['u_dpname'] = $member::getUDpTypes()[$member->u_dp_type];
        $o['u_brmanager'] = $member->u_scope == '部门级'? 1 :0 ;
        return $o;
    }
}